/**
 * 请求工具类
 * @author yuand
 */

import axios from 'axios';
import { getToken } from '@/utils/auth';
import { streamRequest } from '@/utils/streamRequest';
import { globalMessage } from './globalMessage';

const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:20080/',
  timeout: 60000,
});

// 请求拦截器
request.interceptors.request.use( (config) => {
  const token = getToken();
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
},
(error) => {
  return Promise.reject(error);
}
  
);


// 响应拦截器
request.interceptors.response.use(
  (response) => {
    // 检查接口返回是否成功
    const { data } = response;
    if (data && data.success === false) {
      // 如果返回失败，显示错误信息
      globalMessage.error(data.message || '请求失败');
      return Promise.reject(new Error(data.message || '请求失败'));
    }
    // 成功则返回数据
    return response.data.data;
  },
  (error) => {
    // 处理请求失败的情况
    const errorMsg = error.response?.data?.message || error.message || '网络请求异常';
    globalMessage.error(errorMsg);
    return Promise.reject(error);
  }
);


const _streamRequestUrlParse = (url: string) => {
  const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:20080/';
  if(!url.includes('http')){
    if(baseUrl.endsWith('/') && url.startsWith('/')){
      url = baseUrl + url.slice(1);
    } else if(!baseUrl.endsWith('/') && !url.startsWith('/')){
      url = baseUrl + '/' + url;
    }
  }
  return url;
}

const _streamRequest = {
  get: (url: string, options: any) => {
    return streamRequest(_streamRequestUrlParse(url), options);
  },
  post: (url: string, data: any, options: any) => {
    return streamRequest(_streamRequestUrlParse(url), {
      method: 'POST',
      body: JSON.stringify(data),
      ...options
    });
  }
}; 


export { request, _streamRequest as streamRequest}; 